package widget;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by LLAP on 2017/12/13.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class TRow extends JPanel {
    private LinkedList<TComponent> dataSet;
    public TRow() {
        super(new GridBagLayout());
        //super(new GridLayout(1, column, 10, 10));
        dataSet = new LinkedList<>();
    }

    public Component add(TComponent comp) {
        return this.add(comp, 3);
    }
    public Component add(TComponent comp, int width) {
        Component title = null;
        int offset;
        if (!comp.getComment().equals("")) {
            title = super.add(new JLabel(comp.getComment(), SwingConstants.RIGHT));
            offset = 1;
        }
        else offset = 0;
        Component ret = super.add(comp.field);
        if (title != null) {
            ((GridBagLayout) this.getLayout()).setConstraints(
                    title,
                    new GridBagConstraints() {{
                        fill = GridBagConstraints.BOTH;
                        gridwidth = gridheight = 1;
                        insets = new Insets(5, 5, 5, 5);
                        weightx = weighty = 1;
                        gridx = gridy = 0;
                    }}
            );
        }
        ((GridBagLayout)this.getLayout()).setConstraints(
                ret,
                new GridBagConstraints() {{
                    fill = GridBagConstraints.BOTH;
                    gridwidth = gridheight = 1;
                    insets = new Insets(5, 5, 5, 5);
                    weightx = width;
                    weighty = 1;
                    gridx = offset;
                    gridy = 0;
                }}
        );
        dataSet.add(comp);
        return ret;
    }

    public void clear() {
        for (TComponent i : dataSet) {
            i.clear();
        }
    }

    public HashMap<String, Object> getData() throws IllegalArgumentException {
        try {
            return new HashMap<String, Object>() {{
                for (TComponent c : dataSet) {
                    HashMap<String, Object> d = c.getData();
                    if (d != null) putAll(d);
                }
            }};
        }
        catch (IllegalArgumentException e) {
            throw e;
        }
    }

    public TRow setHeight(int height) {
        this.setSize(this.getWidth(), height);
        return this;
    }
}
